#/usr/bin/env python
#coding=utf8
"""
# Author: kellanfan
# Created Time : Thu 10 Jan 2019 12:00:36 PM CST

# File Name: utils.py
# Description: 这里会记录一些小技巧函数

"""

def utf8str(s):
    #返回utf8编码的字符串
    encoding = 'utf-8'
    if not isinstance(s, basestring):
        try:
            return str(s)
        except UnicodeEncodeError:
            return unicode(s).encode(encoding)
    elif isinstance(s, unicode):
        return s.encode(encoding)
    else:
        return s

def encode_pairs(pairs, lsep, tsep):
    """Return string joined by seperator
    >>> p = [('a',1), ('b',2)]
    >>> encode_pairs(p, '|', ':')
    'a:1|b:2'
    """
    return lsep.join([tsep.join([utf8str(i) for i in p]) for p in pairs])

def check_ping(ip, tries=2, delay=1):
    check_ip_count = 0
    while check_ip_count < tries:
        result = exec_cmd('ping -c 1 -w 2 {0}'.format(ip))
        if result['ret'] != 0:
            check_ip_count += 1
            time.sleep(delay)
        else:
            break
    else:
        logger.error("Check the host [{0}] ping connection failed!".format(ip))
        return -1

    return 0


def check_ssh(ip, tries=3, delay=3):
    check_ssh_count = 0
    while check_ssh_count < tries:
        result = exec_cmd('ssh -o ConnectTimeout=2 root@{0} echo'.format(ip))
        if result['ret'] != 0:
            check_ssh_count += 1
            time.sleep(delay)
        else:
            break
    else:
        logger.error("Check the host [{0}] ssh connection failed!".format(ip))
        return -1

    return 0


def get_local_ips():
    default_gateway_dev = exec_cmd("ip route | awk '/^default/ {print $5}'")['out']
    ips = exec_cmd("ip -f inet -o addr | awk '{print $2,$4}' | awk -F '/' '{print $1}'")['out'].split('\n')

    ips_dict = {
        value.split()[0] : value.split()[1]
        for value in ips
    }

    if default_gateway_dev:
        ips_dict['default'] = ips_dict[default_gateway_dev]

    return ips_dict
